<template>
  <div class="department" @click="closePopover">
    <el-row style="height: 100%">
      <el-col :span="6" style="height: 100%" class="left">
        <pageCard :title-name="'部门树'" :type="'pageTitle'">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="padding-bottom: 10px" />
          <el-scrollbar style="height: calc(100% - 42px)" class="treeContent">
            <el-tree
              ref="tree"
              :data="departmentTree"
              default-expand-all
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :props="defaultProps"
              @node-click="nodeClick"
            >
              <span
                slot-scope="{ node, data }"
                class="treeRow"
                @mouseenter="mouseenter(data)"
                @mouseleave="mouseleave(data)"
              >
                <i class="el-icon-office-building" />
                <span style="padding-left: 5px">{{ node.label }}</span>
                <el-popover
                  id="popoverDiv"
                  v-model="data.popoverShow"
                  popper-class="departmentPopover"
                  placement="right"
                  width="200"
                  trigger="manual"
                >
                  <ul v-show="popoverType === 'index'" class="popoverUl">
                    <li
                      v-permission="['system:department:edit']"
                      class="popoverItem"
                      @click="handleClick('edit', data)"
                    >
                      {{ data.company ? '修改公司名称' : '修改部门' }}
                    </li>
                    <li v-permission="['system:department:add']" class="popoverItem" @click="clickAddDept(data)">
                      {{ data.company ? '添加部门' : '添加子部门' }}
                    </li>
                    <li
                      v-show="!data.company"
                      v-permission="['system:department:del']"
                      class="popoverItem"
                      style="color: red"
                      @click="clickDeleteDept(data)"
                    >
                      删除
                    </li>
                  </ul>
                  <div v-show="popoverType === 'editName'" class="editName">
                    <el-input
                      v-if="!popoverNode.company"
                      v-model="formData.departmentCode"
                      maxlength="50"
                      show-word-limit
                      placeholder="请输入部门编号"
                      class="show-word-limit"
                      style="margin-bottom: 10px"
                    />
                    <el-input
                      v-model="formData.departmentName"
                      maxlength="50"
                      show-word-limit
                      :placeholder="popoverNode.company ? '请输入公司名称' : '请输入部门名称'"
                      class="show-word-limit"
                    />
                    <el-button plain class="popoverBtn" @click="popoverType = 'index'">取 消</el-button>
                    <el-button type="primary" class="popoverBtn" @click="submitSetName(data)">确 定</el-button>
                  </div>
                  <svg-icon
                    v-show="data.show"
                    slot="reference"
                    icon-class="treeUnfold"
                    class="iconTreeUnfold"
                    @click="setPopoverShowTrue(data)"
                  />
                </el-popover>
              </span>
            </el-tree>
          </el-scrollbar>
        </pageCard>
      </el-col>
      <el-col :span="18" style="height: 100%">
        <pageCard :title-name="'组织架构图'" style="height: 100%" :type="'pageTitle'">
          <template #header>
            <el-button v-permission="['system:department:download']" plain class="topBtn" @click="downloadImg">
              下 载
            </el-button>
          </template>
          <el-scrollbar style="height: 100%">
            <orgChart ref="orgChart" :org-chart-data="orgChartData" />
          </el-scrollbar>
        </pageCard>
      </el-col>
    </el-row>
    <el-dialog
      :title="dialogTitle"
      class="addDeptDialog"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input
        v-model="formData.departmentCode"
        placeholder="请输入部门编号"
        maxlength="50"
        class="show-word-limit"
        show-word-limit
        style="margin-bottom: 10px"
      />
      <el-input
        v-model="formData.departmentName"
        :placeholder="dialogTitle === '添加部门' ? '请输入部门名称' : '请输入子部门名称'"
        maxlength="50"
        class="show-word-limit"
        show-word-limit
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogAddDept()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentNodeTree } from '@/api/table'
import {
  initDepartment,
  updateCompanyName,
  addDepartmentNode,
  updateDepartment,
  deleteDepartmentNode
} from '@/api/system-management'
import pageCard from '@/components/page/pageCard'
import orgChart from './components/orgChart'
import '@/styles/vueOrgTree.less'
export default {
  name: 'Department',
  components: {
    pageCard,
    orgChart
  },
  data() {
    return {
      filterText: '',
      departmentTree: [],
      dialogTitle: '',
      orgChartData: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      popoverNode: {},
      popoverType: 'index',
      dialogVisible: false,
      addNode: null,
      formData: {}
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 获取数据
    getData() {
      this.departmentTree = []
      getDepartmentNodeTree().then((res) => {
        this.orgChartData = res.data
        this.departmentTree.push(res.data)
        this.$refs.orgChart.toggleExpand(this.orgChartData, true)
      })
    },
    handleClick(name, data = null) {
      if (name === 'edit') {
        this.popoverType = 'editName'
        if (data.company) {
          this.formData = {
            departmentName: data.label
          }
        } else {
          initDepartment({ departmentId: data.id }).then((res) => {
            this.formData = {
              departmentCode: res.data.departmentCode,
              departmentName: res.data.departmentName
            }
          })
        }
      }
    },
    // 修改名字
    submitSetName(data) {
      if (this.popoverNode.company) {
        const obj = {
          companyName: this.formData.departmentName,
          companyId: data.id
        }
        updateCompanyName(obj).then((res) => {
          this.$notify({
            title: '成功',
            message: '修改公司名称成功',
            type: 'success'
          })
          this.setPopoverShowFalse(this.departmentTree)
          this.getData()
        })
      } else {
        const obj = {
          departmentCode: this.formData.departmentCode,
          departmentName: this.formData.departmentName,
          departmentId: data.id
        }
        updateDepartment(obj).then((res) => {
          this.$notify({
            title: '成功',
            message: '修改部门名称成功',
            type: 'success'
          })
          this.setPopoverShowFalse(this.departmentTree)
          this.getData()
        })
      }
    },
    // 下载组织架构图
    downloadImg() {
      this.$refs.orgChart.generatorImage()
    },
    // 点击添加部门
    clickAddDept(node) {
      if (node.company) {
        this.dialogTitle = '添加部门'
      } else {
        this.dialogTitle = '添加子部门'
      }
      this.dialogVisible = true
      this.addNode = node
      this.formData = {}
    },
    // 点击删除部门
    clickDeleteDept(node) {
      this.$confirm('此操作将永久删除该"' + node.label + '"与其子部门, 是否确定要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDepartmentNode({ departmentId: node.id }).then((res) => {
            this.$notify({
              title: '成功',
              message: '删除部门成功',
              type: 'success'
            })
            this.setPopoverShowFalse(this.departmentTree)
            this.getData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 确定部门添加
    dialogAddDept() {
      const obj = {
        name: this.formData.departmentName,
        departmentCode: this.formData.departmentCode,
        parentId: this.addNode.company ? null : this.addNode.id
      }
      addDepartmentNode(obj).then((res) => {
        this.$notify({
          title: '成功',
          message: '添加子部门成功',
          type: 'success'
        })
        this.dialogVisible = false
        this.getData()
      })
    },
    // 关闭部门添加
    handleClose(done) {
      this.$confirm('确认取消' + this.dialogTitle + '？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 以下树函数
    // 过滤树函数
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 以下函数都是和popover有关的函数
    setInitTreeData() {
      for (const item of this.departmentTree) {
        item['popoverShow'] = false
        item['show'] = false
        if (item.children) {
          this.setPopoverShowFalse(item.children)
        }
      }
    },
    // 鼠标悬浮进tree
    mouseenter(data) {
      this.$set(data, 'show', true)
    },
    // 鼠标悬浮出tree
    mouseleave(data) {
      if (this.popoverNode !== {} && this.popoverNode.id === data.id) {
        this.$set(data, 'show', true)
      } else {
        this.$set(data, 'show', false)
      }
    },
    // 点击节点
    async nodeClick(node) {
      await this.setPopoverShowFalse(this.departmentTree)
      // eslint-disable-next-line require-atomic-updates
      node.show = true
      this.formData = {
        departmentCode: '',
        departmentName: ''
      }
      this.popoverNode = {}
    },
    // 点击popover区域以外关闭popover
    closePopover() {
      var sp = document.getElementById('popoverDiv')
      if (sp) {
        if (!sp.contains(event.target)) {
          // 这句是说如果我们点击到了id为popoverDiv以外的区域
          this.setPopoverShowFalse(this.departmentTree)
          this.popoverNode = {}
        }
      }
    },
    // 让部门树有各种show属性
    // 使节点popoverShow为true
    setPopoverShowTrue(data) {
      const test = JSON.parse(JSON.stringify(data))
      setTimeout(() => {
        data.popoverShow = !test.popoverShow
        if (data.popoverShow) {
          this.popoverNode = data
        } else {
          this.popoverNode = {}
        }
        this.$set(data, 'show', true)
      }, 100)
    },
    // 使节点popoverShow为false
    setPopoverShowFalse(treeData) {
      this.popoverType = 'index'
      for (const item of treeData) {
        item.popoverShow = false
        this.$set(item, 'show', false)
        if (item.children) {
          this.setPopoverShowFalse(item.children)
        }
      }
    }
  }
}
</script>
<style lang="less">
.departmentPopover {
  padding: 0px;

  .popoverUl {
    margin: 0;
    padding: 0px;
    .popoverItem {
      list-style-type: none !important;
      padding: 0 15px;
      cursor: pointer;
      line-height: 40px;
    }
    .popoverItem:hover {
      background-color: #f0f7ff;
    }
  }

  .editName {
    padding: 10px;
    width: 200px;
  }

  .popoverBtn {
    margin-top: 10px;
    padding: 8px 25px;
  }
}
.addDeptDialog {
  /deep/.el-dialog__header {
    padding: 20px 20px 10px 20px;
  }
}
</style>
<style lang="less" scoped>
@import '../../styles/pageTableTop.scss';
.department {
  height: 99%;
  /deep/ .el-dialog__title {
    font-size: 17px;
  }
  /deep/ .el-dialog__body {
    padding: 10px 20px 20px;
  }
  .left {
    /deep/.el-scrollbar__view {
      height: 100%;
    }
    .treeContent {
      /deep/.el-scrollbar__view {
        height: auto;
      }
    }
  }
  /deep/.el-tree {
    border-right: none;
    .treeRow {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .el-tree-node__expand-icon {
      font-size: 18px;
      position: relative;
      left: 5px;
    }

    .el-tree-node .is-current {
      background-color: #f5f7fa;
    }
    .el-tree-node__expand-icon {
      float: right;
      // margin-right: 1.5625rem !important;
    }
    .el-tree-node__content {
      height: 2.5rem;
      line-height: 2.5rem;
      font-size: 16px;
    }
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      background: #ecf5ff;
    }
  }
  /deep/.el-input-group__append {
    padding: 0px 10px;
  }
  .iconTreeUnfold {
    font-size: 14px;
    display: flex;
    align-items: center;
  }
}
</style>
